package com.tanhua.manage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.manage.domain.UserFreeze;
import com.tanhua.manage.mapper.UserFreezeMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.*;

@Service
public class UserFreezeService extends ServiceImpl<UserFreezeMapper, UserFreeze> {

    @Autowired(required = false)
    private UserFreezeMapper userFreezeMapper;

    @Reference
    private UserApi userApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 接口名称：用户冻结操作
     *
     * @param paramMap
     * @return
     */
    public ResponseEntity<Object> usersFreeze(Map<String, Object> paramMap) {
        //获取数据
        Integer userId = (Integer) paramMap.get("userId");
        Integer freezingTime = Integer.parseInt(paramMap.get("freezingTime").toString());
        Integer freezingRange = Integer.parseInt(paramMap.get("freezingRange").toString());
        String reasonsForFreezing = paramMap.get("reasonsForFreezing").toString();
        String frozenRemarks = paramMap.get("frozenRemarks").toString();
        //封装数据
        Date date = new Date();
        long sevenTimes = date.getTime() + 7 * 24 * 60 * 60 * 1000;
        long threeTimes = date.getTime() + 3 * 24 * 60 * 60 * 1000;
        long hundredTimes = date.getTime() + 100L * 365L * 24L * 60L * 60L * 1000L;
        Date afterSevenDate = new Date(sevenTimes);
        Date afterThreeDate = new Date(threeTimes);
        Date afterHundredDate = new Date(hundredTimes);
        //创建冻结表
        UserFreeze userFreeze = new UserFreeze();
        userFreeze.setUserId(userId);
        userFreeze.setFreezingTime(freezingTime);//冻结时间
        userFreeze.setFreezingRange(freezingRange);//冻结范围
        userFreeze.setReasonsForFreezing(reasonsForFreezing);//冻结理由
        userFreeze.setFrozenRemarks(frozenRemarks);//冻结备注
        userFreeze.setStatus(0); //冻结状态
        userFreeze.setFreezeTime(date); //冻结开始时间
        //设置解冻时间
        switch (userFreeze.getFreezingRange()) {
            case 1: { //封3天
                //设置解冻时间
                userFreeze.setUnfreezeTime(afterThreeDate);
                //把冻结范围存入redis里面
                redisTemplate.opsForValue().set("FREEZE_TYPE_" + userId, userFreeze.getFreezingRange().toString(), Duration.ofMillis(afterThreeDate.getTime()));
                break;
            }
            case 2: { //封7天
                userFreeze.setUnfreezeTime(afterSevenDate);
                redisTemplate.opsForValue().set("FREEZE_TYPE_" + userId, userFreeze.getFreezingRange().toString(), Duration.ofMillis(afterSevenDate.getTime()));
                break;
            }
            case 3: { //封永久
                userFreeze.setUnfreezeTime(afterHundredDate);
                redisTemplate.opsForValue().set("FREEZE_TYPE_" + userId, userFreeze.getFreezingRange().toString());
                break;
            }
        }
        if (1 == userFreeze.getFreezingRange()) {
            User user = userApi.findById(userId);
            //1. 要加密的数据
            Map<String, Object> map = new HashMap<>();
            map.put("id", userId);
            map.put("mobile", user.getMobile());
            String token = Jwts.builder().setClaims(map)
                    .signWith(SignatureAlgorithm.HS256, "itcast").compact();
            redisTemplate.delete("TOKENY_KEY_" + token);
        }

        //把封装的数据写入 冻结表
        int row = userFreezeMapper.insert(userFreeze);
        //返回结果
        String message = "操作失败";
        if (row > 0) {
            message = "操作成功";
            //查询用户修改userStatus
            //帮默认状态修改为冻结状态
            UserInfo userInfo = userInfoApi.findById(userId.longValue());
            userInfo.setUserStatus("2");
            userInfoApi.update(userInfo);
        }
        //返回
        return ResponseEntity.ok(message);
    }


    /**
     * 接口名称：用户解冻操作
     */
    public ResponseEntity<Object> usersUnfreeze(Map<String, Object> paramMap) {
        //获取数据
        Integer userId = (Integer) paramMap.get("userId");
        String reasonsForThawing = paramMap.get("frozenRemarks").toString(); //解冻理由
        //封装数据
        UpdateWrapper<UserFreeze> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId);
        updateWrapper.eq("status", 0);
        updateWrapper.isNull("reasons_for_thawing");//解冻理由为空，证明该用户处于冻结状态
        //修改冻结表，帮解冻理由，和解冻时间存入表中
        UserFreeze userFreeze = new UserFreeze();
        userFreeze.setUnfreezeTime(new Date());
        userFreeze.setReasonsForThawing(reasonsForThawing);  //解冻理由
        userFreeze.setStatus(2); //人工解冻
        int row = userFreezeMapper.update(userFreeze, updateWrapper);
        //返回数据
        String message = "操作失败";
        if (row > 0) {
            message = "操作成功";
            //查询用户修改userStatus
            UserInfo userInfo = userInfoApi.findById(userId.longValue());
            userInfo.setUserStatus("1");//未冻结
            userInfoApi.update(userInfo);
            redisTemplate.delete("FREEZE_TYPE_" + userId);//删除redis中，冻结的天数
        }

        return ResponseEntity.ok(message);
    }


    /**
     * 自动解封
     */
    public void autoUnFreeze() {
        Date now = new Date();
        //查询封禁用户
        QueryWrapper<UserFreeze> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        List<UserFreeze> userFreezeList = list(queryWrapper);
        //判断查到数据不为空
        if (userFreezeList != null) {
            for (UserFreeze userFreeze1 : userFreezeList) {
                //解冻时间小于当前时间，证明该用户已经解冻
                if (userFreeze1.getUnfreezeTime().getTime() < now.getTime()) {
                    //封装数据
                    UpdateWrapper<UserFreeze> updateWrapper = new UpdateWrapper<>();
                    //查找满足解冻条件的用户
                    updateWrapper.eq("user_id", userFreeze1.getUserId());
                    updateWrapper.eq("status", 0);
                    updateWrapper.isNull("reasons_for_thawing");
                    //修改Status
                    UserFreeze userFreeze = new UserFreeze();
                    userFreeze.setStatus(1);
                    userFreeze.setReasonsForThawing("封禁时间结束，自动解封");

                    int row = userFreezeMapper.update(userFreeze, updateWrapper);
                    if (row > 0) {
                        //查询用户修改userStatus
                        UserInfo userInfo = userInfoApi.findById(userFreeze1.getUserId().longValue());
                        userInfo.setUserStatus("1");
                        userInfoApi.update(userInfo);
                    }
                }
            }
        }
    }
}


